//
//  MailListViewController.m
//  SelfDriving
//
//  Created by apple on 16/3/15.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "MailListViewController.h"
#import "BlackCell.h"
#import <AddressBook/AddressBook.h>
#import "BusinessService+WD.h"
@interface MailListViewController()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *table;
@end
@implementation MailListViewController
{   NSMutableArray *datas;//存在好友绑定
    NSMutableArray *data;//通讯录
    NSMutableArray *sdata;
}

-(void)viewDidLoad{
    data = [[NSMutableArray alloc]init];
    sdata = [[NSMutableArray alloc]init];
    datas = [[NSMutableArray alloc]init];
    int __block tip=0;
    //声明一个通讯簿的引用
    ABAddressBookRef addBook =nil;
    //因为在IOS6.0之后和之前的权限申请方式有所差别，这里做个判断
    if ([[UIDevice currentDevice].systemVersion floatValue]>=6.0) {
        //创建通讯簿的引用
        addBook=ABAddressBookCreateWithOptions(NULL, NULL);
        //创建一个出事信号量为0的信号
        dispatch_semaphore_t sema=dispatch_semaphore_create(0);
        //申请访问权限
        ABAddressBookRequestAccessWithCompletion(addBook, ^(bool greanted, CFErrorRef error)        {
            //greanted为YES是表示用户允许，否则为不允许
            if (!greanted) {
                tip=1;
            }
            //发送一次信号
            dispatch_semaphore_signal(sema);
        });
        //等待信号触发
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }else{
        //IOS6之前
        addBook =ABAddressBookCreate();
    }
    if (tip) {
        //做一个友好的提示
        UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请您设置允许APP访问您的通讯录-设置>隐私" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alart show];
     }
    //获取所有联系人的数组
    CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addBook);
    //获取联系人总数
    CFIndex number = ABAddressBookGetPersonCount(addBook);
    //进行遍历
    for (NSInteger i=0; i<number; i++) {
        //获取联系人对象的引用
        ABRecordRef  people = CFArrayGetValueAtIndex(allLinkPeople, i);
        //获取当前联系人名字
        NSString*firstName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty));
        firstName = firstName?firstName:@"";
        //获取当前联系人姓氏
        NSString*lastName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonLastNameProperty));
        lastName = lastName?lastName:@"";

        //获取当前联系人头像图片
        NSData*userImage=(__bridge NSData*)(ABPersonCopyImageData(people));
        
           NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        //读取电话多值
        ABMultiValueRef phone = ABRecordCopyValue(people, kABPersonPhoneProperty);
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //获取电话Label
            NSString * personPhoneLabel = (NSString*)CFBridgingRelease(ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k)));
            //获取該Label下的电话值
            NSString * personPhone = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phone, k));
            [dic setObject:[NSString stringWithFormat:@"%@%@",personPhoneLabel,personPhone] forKey:@"phone"];
        }
        [dic setObject:[NSString stringWithFormat:@"%@%@",lastName,firstName] forKey:@"name"];
        [dic setObject:userImage?userImage:@"" forKey:@"img"];

        [data addObject:dic];
 
//        NSLog(@"phonedata.count->添加后%lu",(unsigned long)data.count);
    }
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//    NSMutableString *str = [[NSMutableString alloc]init];
//    for (int i = 0; i<sdata.count; i++) {
//        NSMutableDictionary *dic = [sdata objectAtIndex:i];
//        [str appendFormat:@"%@,",[dic objectForKey:@"phone"]];
//    }
//    [dic setObject:str forKey:@"phone"];
//    [[BusinessService shareInstance]importContact:dic success:^(id result) {
//        datas = result;
//        [_table reloadData];
//    } failure:^(id result) {
//        [SVProgressHUD showErrorWithStatus:result];
//    }];
    
    
    
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return datas.count;
    }
    return data.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.section == 0) {
//        LoginResponseModel *model = [datas objectAtIndex:indexPath.row];
//        BlackCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FriendsCell"];
//        
//        while ([cell.selectView.subviews lastObject] != nil) {
//            [(UIView*)[cell.selectView.subviews lastObject] removeFromSuperview];
//        }
//        
//        cell.imghead.image = [UIImage imageNamed:@"notimgs"];
//        NSData *data = model.headsmall;
//        if ([data isKindOfClass:[NSData class]]) {
//            UIImage  *img = [UIImage imageWithData:data];
//            cell.imghead.image = img;
//        }
//        
//        UIButton *btn =[[UIButton alloc]initWithFrame:CGRectMake(10, 10, 20, 20)];
//        [btn setImage:[UIImage imageNamed:@"dx_f.png"] forState:UIControlStateNormal];
//        [btn setImage:[UIImage imageNamed:@"dx_og.png"] forState:UIControlStateSelected];
//        btn.tag = indexPath.row+1;
//        [cell.selectView addSubview:btn];
//        for (int i = 0; i<sdata.count; i++) {
//            NSMutableDictionary *model1 = [sdata objectAtIndex:i];
//            NSString *n1 = [dic objectForKey:@"name"];
//            NSString *n2 = [model1 objectForKey:@"name"];
//            if ([n1 isEqualToString:n2]) {
//                btn.selected = YES;
//            }
//        }
//        cell.imghead.layer.cornerRadius = cell.imghead.frame.size.width/2;
//        cell.imghead.clipsToBounds = YES;
//        cell.labelname.text = [dic objectForKey:@"name"];
//        cell.btnClater.hidden = YES;
//        return  cell;
//
//    }
    if (indexPath.section == 1) {
        NSMutableDictionary *dic = [data objectAtIndex:indexPath.row];
        BlackCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FriendsCell"];
        
        while ([cell.selectView.subviews lastObject] != nil) {
            [(UIView*)[cell.selectView.subviews lastObject] removeFromSuperview];
        }
        
        cell.imghead.image = [UIImage imageNamed:@"notimgs"];
        NSData *data = [dic objectForKey:@"img"];
        if ([data isKindOfClass:[NSData class]]) {
            UIImage  *img = [UIImage imageWithData:data];
            cell.imghead.image = img;
        }
        
        UIButton *btn =[[UIButton alloc]initWithFrame:CGRectMake(10, 10, 20, 20)];
        [btn setImage:[UIImage imageNamed:@"dx_f.png"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"dx_og.png"] forState:UIControlStateSelected];
        btn.tag = indexPath.row+1;
        [cell.selectView addSubview:btn];
        for (int i = 0; i<sdata.count; i++) {
            NSMutableDictionary *model1 = [sdata objectAtIndex:i];
            NSString *n1 = [dic objectForKey:@"name"];
            NSString *n2 = [model1 objectForKey:@"name"];
            if ([n1 isEqualToString:n2]) {
                btn.selected = YES;
            }
        }
        cell.imghead.layer.cornerRadius = cell.imghead.frame.size.width/2;
        cell.imghead.clipsToBounds = YES;
        cell.labelname.text = [dic objectForKey:@"name"];
        cell.btnClater.hidden = YES;
        return  cell;
    }
    return nil;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UIButton *btn = (UIButton *)[self.view viewWithTag:indexPath.row+1];
    btn.selected = !btn.selected;
    NSMutableDictionary *model = [data objectAtIndex:indexPath.row];
    if (btn.selected) {
        [sdata addObject:model];
    }else{
        [sdata removeObject:model];
    }
}
#pragma  mark 保存
- (IBAction)submitAction:(UIBarButtonItem *)sender {
  
    
    
    
}


- (IBAction)backActino:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


@end
